package com.pocketsweet.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.ActionSheetDialog;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.ActionSheetDialog.OnSheetItemClickListener;
import com.pocketsweet.ui.uilib.ActionSheetDialog.SheetItemColor;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;
import com.pocketsweet.utils.selectPicUtils;

@ContentView(R.layout.activity_indentification_photo)
public class IdentificationPhoto extends BaseActivity implements
		OnClickListener {
	private static final int REQUEST_CODE_SELECT_PHOTO = 0x01;
	private static final int REQUEST_CROP = 0x02;
	private MLUser mlUser = new MLUser();
	public static AVFile photo;
	public static Uri cropPath;
	public static String photoPath;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.btn_sure)
	private static Button btn_sure;

	@ViewInject(R.id.imgIdentification)
	private static ImageView imgIdentification;

	@ViewInject(R.id.imgAdd)
	private static ImageView imgAdd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlUser = UserService.getCurrentUser();
		setHeaderFunction();
		initView();
	}

	private void initView() {
		imgAdd.setOnClickListener(this);
		btn_sure.setOnClickListener(this);
		// UserService.displayRound("drawable://"
		// + R.drawable.identification_photo, imgIdentification);
//		if (photo != null) {
//			photo = null;
//		}
//		if (cropPath != null) {
//			cropPath = null;
//		}
		if (!StringUtils.isEmpty(photoPath)) {
			UserService.displayRound(photoPath, imgAdd);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("照片认证");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				IdentificationPhoto.this.finish();
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.imgAdd:
			new ActionSheetDialog(IdentificationPhoto.this)
					.builder()
					.setCancelable(true)
					.setCanceledOnTouchOutside(true)
					.addSheetItem("从相册选择", SheetItemColor.Gray,
							new OnSheetItemClickListener() {
								@Override
								public void onClick(int which) {
									Intent intent = new Intent();
									intent.setDataAndType(
											MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											"image/*");
									intent.setAction(Intent.ACTION_GET_CONTENT);
									startActivityForResult(intent,
											REQUEST_CODE_SELECT_PHOTO);
									// selectPicUtils.openLocalImage(getActivity());
								}
							})
					.addSheetItem("拍照", SheetItemColor.Gray,
							new OnSheetItemClickListener() {
								@Override
								public void onClick(int which) {
									selectPicUtils
											.openCameraImage(IdentificationPhoto.this);
								}
							}).show();
			break;
		case R.id.btn_sure:
			IdentificationPhoto.this.finish();
			break;
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 600);
		intent.putExtra("outputY", 600);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cropPath);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true);
		intent.putExtra("scale", true);
		intent.putExtra("scaleUpIfNeeded", true);
		startActivityForResult(intent, REQUEST_CROP);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_CANCELED) {
			return;
		}
		switch (requestCode) {
		case selectPicUtils.GET_IMAGE_BY_CAMERA: // 拍照上传
			Uri url = selectPicUtils.imageUriFromCamera;
			if (url != null) {
				String sImagePath = ToolKits.getImgRealPathFromURI(url,
						IdentificationPhoto.this);
				String copressPath = sImagePath + "_small";
				WindowManager wm = (WindowManager) IdentificationPhoto.this
						.getSystemService(Context.WINDOW_SERVICE);
				int width = wm.getDefaultDisplay().getWidth();
				selectPicUtils.cropBgImage(IdentificationPhoto.this,
						selectPicUtils.imageUriFromCamera, 1, 1, 600, 600);
			}
			break;
		case REQUEST_CODE_SELECT_PHOTO: // 选择图片上传,每次上传一个图片，就会上传到服务器,但是未保存到MLUser

			if (null != data) {
				Uri url1 = data.getData();
				String ImagePath = ToolKits.getImgRealPathFromURI(url1,
						IdentificationPhoto.this);
				File file = new File(ImagePath);
				cropPath = Uri.parse("file://" + file.getAbsolutePath()
						+ "_small");
				startPhotoZoom(Uri.fromFile(file));
			}
			break;
		case selectPicUtils.CROP_IMAGE: // 拍照后的回调
			if (selectPicUtils.cropImageUri != null) {
				File avatarCrop = selectPicUtils.createFileFromUri(
						selectPicUtils.cropImageUri, IdentificationPhoto.this);
				UserService.displayRound(
						"file://" + avatarCrop.getAbsolutePath(), imgAdd);
				photoPath = "file://" + avatarCrop.getAbsolutePath();
				try {
					photo = AVFile.withAbsoluteLocalPath(avatarCrop.getName(),
							avatarCrop.getAbsolutePath());
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			break;
		case REQUEST_CROP: // 选择图片后的回调
			String ImagePath = ToolKits.getImgRealPathFromURI(cropPath,
					IdentificationPhoto.this);
			File file = new File(ImagePath);
			if (file.exists()) {
				try {
					photo = AVFile.withAbsoluteLocalPath(file.getName(),
							file.getAbsolutePath());
					photoPath = "file://" + file.getAbsolutePath();
					// Log.e("==photopath", "photo:"+photoPath+" ");
					UserService.displayRound(photoPath, imgAdd);
					// mGalleryView.addImagePath(ImagePath);// 先显示图片，不上传
					// mAVFileList.add(photo);

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				ToolKits.toast(IdentificationPhoto.this, "文件不存在！");
			}
		default:
			break;
		}
		if (requestCode == REQUEST_CODE_SELECT_PHOTO) {

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 此处写处理的事件
			mlUser.saveInBackground(new SaveCallback() {
				@Override
				public void done(AVException arg0) {
					if (arg0 == null) {
						ToolKits.toast(IdentificationPhoto.this, "修改成功");
					}
				}
			});
			IdentificationPhoto.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
